/**
 * 定义了axios的拦截器，以及封装axios的 get 和 post 请求
 */
import axios from "axios"
import store from "@/store";
import Vue from "vue";
import router from "@/router";
import ElementUI from 'element-ui';

const url ='http://127.0.0.1:9090'
const instance=axios.create({
    timeout: 7000, //请求超时时间
    baseURL: url,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    }
})


/*export function get(shortURL, params) {
    if(params!=null){
        return instance.get(url + shortURL, {
            params,
        });
    }
    instance.get(url + shortURL).then(resp=>{
        console.log(resp)
    })
    /!*instance
        // 3.1url地址
        .get("http://127.0.0.1:9090/lastIndex/getWebAdminJ")
        // 3.2成功时回调函数
        .then((data) => {
            console.log(44444444)
            console.log(data);
        })
        //3.3失败时回调函数
        .catch((err) => {
            console.log(err);
        });*!/
}*/

//封装get和post请求
Vue.prototype.$myAxios=(url, method, params, callback) => {
    const axiosConfig= {
        url: url,
        method: method,
    }
    if(method === 'get'){

        if(params!=null){
            axiosConfig.params= params
        }
    }
    else {
        if(params!=null){
            /*const formData = new FormData()
            for(const key in params) {
                formData.append(key,params[key])
            }*/
            axiosConfig.data= params
        }

    }
    store.commit('SET_LOADING',1) //loading
    instance.request(axiosConfig).then(response => {
        callback(response)

    }).catch(error => {

    }).finally(()=>{
        store.commit('SET_LOADING',0) //无论是否报错都要结束loading
    })
}


export function post(shortURL, data) {
    return axios.post(url + shortURL, data);
}

//前置拦截
instance.interceptors.request.use(req=> {
    console.log("1111111111111122222")
    //config.headers.Authorization=window.localStorage.getItem("userInfo")
    req.headers['Content-Type'] = 'application/json;charset=utf-8';
    if (window.location.pathname != "/login/go") {
        req.headers['Authorization'] = localStorage.getItem("token");
    }
    return req
})

//后置拦截
instance.interceptors.response.use(response=>{
        let res=response.data;
        if(res.code == 200){ //正常情况
            console.log('after')
            return response;
        }
        else if(res.code ==201){ //如果用户已经登录就将登录标记置为true
            store.commit('IS_LOGIN',true) //登录标记
            //alert(store.getters.loginFlag)
            router.push("/index");

            return response;
        }
        else if(res.code == 401){ //token过期
            ElementUI.Message.error(res.message,{duration:5*1000})
            //token过期了我们就得将其都清除
            localStorage.setItem("token",'');
            localStorage.setItem("userInfo",JSON.stringify(''));
            //登录标记置为false
            store.commit('IS_LOGIN',false)
            router.push("/index") //token过期跳转的界面
            return Promise.reject(res.message);
        }
        else if(res.code == 402){ //无权限情况
            ElementUI.Message.error(res.message,{duration:5*1000})
            router.push("/index") //无权返回首页
            return Promise.reject(res.message);
        }
        else if(res.code == 500){
            ElementUI.Message.error(res.message,{duration:5*1000})
            return Promise.reject(res.message);
        }
        else if(res.code == 404){
            ElementUI.Message.error(res.message,{duration:5*1000})
            return Promise.reject(res.message);
        }
    },
    error => { //这是响应包中状态行里的状态码
        console.log('err' + error) // for debug
        if(error.response.status==403){ //未登录或者token过期时候，后端响应打回403码
            localStorage.setItem("token",'');
            localStorage.setItem("userInfo",JSON.stringify(''));
            ElementUI.Message.error("未登录或登录过期",{duration:5*1000})
            //登录标记置为false
            store.commit('IS_LOGIN',false)

            router.push("/index")
            return Promise.reject(error)
        }
        else if(error.response.status==405){ //没有权限
            ElementUI.Message.error("未授权",{duration:5*1000})
            router.push("/index")//无权返回首页
            return Promise.reject(error)
        }
        else if(error.response.status==406){
            localStorage.setItem("token",'');
            localStorage.setItem("userInfo",JSON.stringify(''));
            ElementUI.Message.error("账号已被封禁",{duration:5*1000})
            //登录标记置为false
            store.commit('IS_LOGIN',false)
            router.push("/index")
            return Promise.reject(error)
        }
        return Promise.reject(error)
    })


export default instance



//不进行前置拦截
/*axios.interceptors.request.use(config=>{
    //config.headers.Authorization=window.localStorage.getItem("userInfo")
    config.headers['Content-Type'] = 'application/json;charset=utf-8';
    if (window.location.pathname != "/login/go") {
        config.headers['Authorization'] = localStorage.getItem("token");
    }
    return config;
})

//后置拦截
axios.interceptors.response.use(response=>{
    let res=response.data;
    if(res.code == 200){ //正常情况
        return response;
    }
    else if(res.code ==201){ //访问lastIndex时候如果用户已经登录过了就跳转到index
        router.push("/index");
        return response;
    }
    else if(res.code == 401){ //token过期
        ElementUI.Message.error(res.message,{duration:5*1000})
        //token过期了我们就得将其都清除
        localStorage.setItem("token",'');
        localStorage.setItem("userInfo",JSON.stringify(''));
        router.push("/lastIndex") //token过期跳转的界面
        return Promise.reject(res.message);
    }
    else if(res.code == 402){ //无权限情况
        ElementUI.Message.error(res.message,{duration:5*1000})
        router.push("/lastIndex") //无权跳到登录界面
        return Promise.reject(res.message);
    }
    else if(res.code == 500){
        ElementUI.Message.error(res.message,{duration:5*1000})
        return Promise.reject(res.message);
    }
    else if(res.code == 404){
        ElementUI.Message.error(res.message,{duration:5*1000})
        return Promise.reject(res.message);
    }
},
    error => { //这是响应包中状态行里的状态码
        console.log('err' + error) // for debug
        if(error.response.status==403){ //未登录或者token过期时候，后端响应打回403码
            localStorage.setItem("token",'');
            localStorage.setItem("userInfo",JSON.stringify(''));
            ElementUI.Message.error("未登录或登录过期",{duration:5*1000})
            router.push("/lastIndex")
            return Promise.reject(error)
        }
        else if(error.response.status==405){ //没有权限
            ElementUI.Message.error("未授权",{duration:5*1000})
            router.push("/lastIndex")
            return Promise.reject(error)
        }
        else if(error.response.status==406){
            localStorage.setItem("token",'');
            localStorage.setItem("userInfo",JSON.stringify(''));
            ElementUI.Message.error("账号已被封禁",{duration:5*1000})
            router.push("/lastIndex")
            return Promise.reject(error)
        }
        return Promise.reject(error)
    })*/
